package com.gitee.webdav.kernel;

import cn.hutool.core.io.unit.DataSizeUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.smartboot.http.server.impl.Request;
import org.smartboot.socket.extension.plugins.AbstractPlugin;
import org.smartboot.socket.transport.AioSession;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author hongda.li
 */
@Slf4j
public class ResourceMonitor extends AbstractPlugin<Request> {
    /**
     * 定时输出速率
     */
    @Getter
    private final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);

    /**
     * 周期内读的总数据量
     */
    private final LongAdder read = new LongAdder();

    /**
     * 周期内写的总数据量
     */
    private final LongAdder write = new LongAdder();

    public ResourceMonitor() {
        this.executor.scheduleAtFixedRate(() -> {
            long readSize = this.read.sumThenReset();
            if (readSize > 0 && log.isDebugEnabled()) {
                log.debug("网络读取速率 : {}/秒", DataSizeUtil.format(readSize));
            }
            long writeSize = this.write.sumThenReset();
            if (writeSize > 0 && log.isDebugEnabled()) {
                log.debug("网络写入速率 : {}/秒", DataSizeUtil.format(writeSize));
            }
        }, 0, 1, TimeUnit.SECONDS);
    }

    @Override
    public void afterRead(AioSession session, int readSize) {
        this.read.add(readSize);
    }

    @Override
    public void afterWrite(AioSession session, int writeSize) {
        this.write.add(writeSize);
    }
}
